package com.example.enews.viewmodels

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import com.example.enews.models.News
import com.example.enews.repositories.NewsRepository

class NewsViewModel : ViewModel() {
    private val _newsList = MutableLiveData<List<News>>()
    val newsList: LiveData<List<News>> = _newsList

    // 标记数据是否已加载
    private var dataLoaded = false

    init {
        loadNews()
    }

    fun loadNews() {
        if (dataLoaded) return // 如果数据已加载，不再重复加载

        viewModelScope.launch {
            delay(1000) // 模拟网络延迟
            val news = NewsRepository.getLatestNews()
            _newsList.value = news
            dataLoaded = true
        }
    }

    // 添加刷新功能
    fun refreshNews() {
        viewModelScope.launch {
            delay(1000)
            val news = NewsRepository.getLatestNews()
            _newsList.value = news
            dataLoaded = true
        }
    }
}